package mytool

import (
	"database/sql"
	"fmt"

	_ "github.com/mattn/go-sqlite3"
)

var Dbpath string

func init() {
	cfg := Getconfig()
	Dbpath = cfg.Section("").Key("dbpath").String()
}

func UpdateByPara(runsql string, runparams ...interface{}) int64 {
	db, _ := sql.Open("sqlite3", Dbpath)
	defer db.Close()
	stmt, err := db.Prepare(runsql)
	defer stmt.Close()
	if err != nil {
		fmt.Println(err)
	}
	res, err := stmt.Exec(runparams...)
	if err != nil {
		fmt.Println(err)
	}
	reslen, err := res.RowsAffected()
	if err != nil {
		fmt.Println(err)
	}
	return reslen
}

func UpdateNoPara(runsql string) int64 {
	db, _ := sql.Open("sqlite3", Dbpath)
	defer db.Close()
	stmt, err := db.Prepare(runsql)
	defer stmt.Close()
	if err != nil {
		fmt.Println(err)
	}
	res, err := stmt.Exec()
	if err != nil {
		fmt.Println(err)
	}
	reslen, err := res.RowsAffected()
	if err != nil {
		fmt.Println(err)
	}
	return reslen
}

func SelectByPara(runsql string, runparams ...interface{}) *sql.Rows {
	db, _ := sql.Open("sqlite3", Dbpath)
	defer db.Close()
	stmt, err := db.Prepare(runsql)
	defer stmt.Close()
	if err != nil {
		fmt.Println(err)
	}
	rows, err := stmt.Query(runparams...)
	if err != nil {
		fmt.Println(err)
	}
	return rows
}

func SelectNoPara(runsql string) *sql.Rows {
	db, _ := sql.Open("sqlite3", Dbpath)
	defer db.Close()
	stmt, err := db.Prepare(runsql)
	defer stmt.Close()
	if err != nil {
		fmt.Println(err)
	}
	rows, err := stmt.Query()
	if err != nil {
		fmt.Println(err)
	}
	return rows
}
